var express = require('express');
var app = express();
app.set('port', process.env.NODE_PORT || 7008);
var http = require("http");

function startServer() {

	var server = http.createServer(app).listen(app.get('port'), function(){

		//依赖模块加载以及未捕获异常处理
		var setup = require('./setup');
		setup.handleUncaughtException(app);
		setup.mountModules(app, server);
		setup.registerController(app);
		setup.error404(app);
		// setup.initCron();
		// registerSeriveOnZookeeper();
		console.log( 'Message Service started in ' + app.get('env') +
		' mode on http://localhost:' + app.get('port') +
		'; press Ctrl-C to terminate.' );

	});

}

//如果直接运行次模块
if(require.main === module){
	startServer();
}
else{
//通过require获得此模块，用于在集群模式下启动应用
	module.exports = startServer;
}











// var rr = require('rr');

// var i = 0;
// function printNextServer(children){
// 	while(i++ < 10){
// 		console.log(rr(children));
// 	}
// }

// function listChildren(client, path) {
//     client.getChildren(
//         path,
//         function (event) {
//             console.log('Got watcher event: %s', event);
//             i = 0;
//             listChildren(client, path);
//         },
//         function (error, children, stat) {
//             if (error) {
//                 console.log(
//                     'Failed to list children of %s due to: %s.',
//                     path,
//                     error
//                 );
//                 return;
//             }

//             console.log('Children of %s are: %j.', path, children);
//             printNextServer(children);
//         }
//     );
// }

// function registerSeriveOnZookeeper( ){

// 	var zookeeper = require('node-zookeeper-client');
// 	var client = zookeeper.createClient('localhost:2181');
// 	var path = '/web/hush-g/pc/127.0.0.0:3000';

// 	client.once('connected',function () {

// 	    client.create(path , zookeeper.CreateMode.EPHEMERAL , function (error) {
// 	        if (error) {
// 	            console.log('Failed to create node: %s due to: %s.', path, error);
// 	        } else {
// 	            console.log('Node: %s is successfully created.', path);
// 	        }
// 	    });

// 	    listChildren(client, '/web/hush-g/parent');
// 	});

// 	client.connect();
// }

// function registerSeriveOnZookeeper( ){

// 	var zookeeper = require('node-zookeeper-client');
// 	var client = zookeeper.createClient('localhost:2181');
// 	var path = '/web/hush-g/pc/127.0.0.1:' + app.get('port');
// 	client.once('connected',function () {

// 	    client.create(path , zookeeper.CreateMode.EPHEMERAL , function (error) {
// 	        if (error) {
// 	            console.log('Failed to create node: %s due to: %s.', path, error);
// 	        } else {
// 	            console.log('Node: %s is successfully created.', path);
// 	        }
// 	    });

// 	});

// 	client.connect();
// }